<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form class="-mb-15px" :model="queryParams" ref="queryFormRef" :inline="true"
             label-width="68px">
      <el-form-item label="日期" prop="date">
        <el-date-picker v-model="queryParams.date" value-format="YYYY-MM-DD HH:mm:ss"
                        type="daterange"
                        start-placeholder="开始日期" end-placeholder="结束日期"
                        :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
                        class="!w-240px" @change="handleQuery"/>
      </el-form-item>
      <el-form-item label="账号" prop="orgId">
        <el-select v-model="queryParams.orgId" placeholder="请选择账号" clearable class="!w-140px"
                   @change="handleQuery">
          <el-option v-for="dict in getIntDictOptions(DICT_TYPE.ASA_ORG_ID)" :key="dict.value"
                     :label="dict.label"
                     :value="dict.value"/>
        </el-select>
      </el-form-item>
      <el-form-item label="国家" prop="countryCode">
        <el-select v-model="queryParams.countries" placeholder="请选择国家" clearable filterable
                   multiple class="!w-240px">
          <el-option v-for="dict in getDictOptions(DICT_TYPE.COUNTRY_OR_REGION)" :key="dict.value"
                     :label="dict.label"
                     :value="dict.value"/>
        </el-select>
      </el-form-item>
      <el-form-item label="应用">
        <el-select v-model="queryParams.adamIds" placeholder="请选择应用" clearable multiple
                   class="!w-240px">
          <el-option v-for="dict in getIntDictOptions(DICT_TYPE.ASA_APP_ID)" :key="dict.value"
                     :label="dict.label" :value="dict.value"/>
        </el-select>
      </el-form-item>
      <el-form-item label="维度">
        <el-select v-model="queryParams.dimension" class="!w-240px" clearable multiple
                   collapse-tags>
          <el-option label="日期" value="date"/>
          <el-option label="国家" value="country_or_region"/>
          <el-option label="应用" value="adam_id"/>
          <el-option label="广告名称" value="campaign_name"/>
        </el-select>
      </el-form-item>
      <el-form-item label="广告指标">
        <el-select v-model="adColumns" multiple class="!w-260px" @change="saveAdsColumnsSession"
                   collapse-tags>
          <el-option label="广告支出" value="localSpendAmount"/>
          <el-option label="广告名称" value="campaignName"/>
          <el-option label="广告展示" value="impressions"/>
          <el-option label="广告点击" value="taps"/>
          <el-option label="点击率" value="ttr"/>
          <el-option label="转化率" value="conversionRate"/>
          <el-option label="广告安装" value="installs"/>
          <el-option label="广告新装" value="newDownloads"/>
          <el-option label="重复安装" value="reDownloads"/>
          <el-option label="转化费用" value="avgCpaAmount"/>
          <el-option label="点击付费" value="avgCptAmount"/>
          <el-option label="千展费用" value="avgCpmAmount"/>
        </el-select>
      </el-form-item>

      <el-form-item label="销售指标">
        <el-select v-model="salesColumns" multiple class="!w-260px"
                   @change="saveSalesColumnsSession" collapse-tags>
          <el-option label="订阅销售额" value="ascSales"/>
          <el-option label="订阅所得" value="ascProceeds"/>
          <el-option label="展示次数" value="ascImpressions"/>
          <el-option label="点击次数" value="ascTaps"/>
          <el-option label="首次安装" value="ascInstalls"/>
          <el-option label="重新安装" value="ascReInstalls"/>
          <el-option label="更新安装" value="ascUptInstalls"/>
          <el-option label="点击率" value="ascTtr"/>
          <el-option label="转化率" value="ascConversionRate"/>
          <el-option label="试订数" value="ascTrial"/>
          <el-option label="试订率" value="trialRate"/>
          <el-option label="订阅数" value="ascRenewal"/>
          <el-option label="退款数" value="ascRefund"/>
          <el-option label="退款销售额" value="ascRefundSales"/>
          <el-option label="退款所得" value="ascRefundProceeds"/>
          <el-option label="自然新增" value="naturallyInstalls"/>
          <el-option label="利润" value="profit"/>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button @click="handleQuery">
          <Icon icon="ep:search" class="mr-5px"/>
          搜索
        </el-button>
        <el-button @click="resetQuery">
          <Icon icon="ep:refresh" class="mr-5px"/>
          重置
        </el-button>
        <el-button type="success" plain @click="handleExport" :loading="exportLoading"
                   v-hasPermi="['asasc:campaign-data:export']">
          <Icon icon="ep:download" class="mr-5px"/>
          导出
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table class="responsive-table" v-loading="loading" :data="list" :stripe="true"
              :show-overflow-tooltip="true" :cell-style="cellStyle">
      <!-- 维度 -->
      <el-table-column v-if="dimensionColumns.includes('date')" label="日期" align="center"
                       prop="date" :min-width="100" sortable fixed/>
      <el-table-column v-if="dimensionColumns.includes('adam_id')" label="应用" align="center"
                       prop="adamId" :min-width="120" sortable fixed>
        <template #default="scope">
          <span :style="scope.$index === list.length - 1 ? 'font-weight: bold;' : ''">
            <span v-if="scope.$index === list.length - 1">总计</span>
            <span v-else><dict-tag :type="DICT_TYPE.ASA_APP_ID" :value="scope.row.adamId"/></span>
          </span>
        </template>
      </el-table-column>
      <el-table-column v-if="dimensionColumns.includes('country_or_region')" label="国家" fixed
                       align="center" prop="countryOrRegion" :min-width="100" sortable>
        <template #default="scope">
          <span
            :style="scope.$index === list.length - 1 ? 'font-weight: bold;' : 'font-size:10pt;'">{{
              formatCountryCode(scope.row.countryOrRegion)
            }}</span>
        </template>
      </el-table-column>
      <el-table-column v-if="dimensionColumns.includes('campaign_name')" label="广告名称"
                       align="center" prop="campaignName" :min-width="130" fixed>
        <template #default="scope">
          <span :style="scope.$index === list.length - 1 ? 'font-weight: bold;' : 'font-size:9pt;'">{{
              scope.row.campaignName
            }}</span>
        </template>
      </el-table-column>
      <!-- 广告指标 -->
      <el-table-column v-if="adColumns.includes('localSpendAmount')" label="广告支出" align="center"
                       :formatter="(row) => fenToYuanFormat(row.localSpendCurrency,
      row.localSpendAmount)" prop="localSpendAmount" :min-width="100" sortable>
        <template #default="scope">
          <span :style="scope.$index === list.length - 1 ? 'font-weight: bold;' : ''">{{
              fenToYuanFormat(scope.row.localSpendCurrency, scope.row.localSpendAmount, 0)
            }}</span>
        </template>
      </el-table-column>
      <el-table-column v-if="adColumns.includes('impressions')" label="广告展示" align="center"
                       prop="impressions" :min-width="90" sortable>
        <template #default="scope">
          <span :style="scope.$index === list.length - 1 ? 'font-weight: bold;' : ''">{{
              scope.row.impressions
            }}</span>
        </template>
      </el-table-column>
      <el-table-column v-if="adColumns.includes('taps')" label="广告点击" align="center" prop="taps"
                       :min-width="90" sortable>
        <template #default="scope">
          <span :style="scope.$index === list.length - 1 ? 'font-weight: bold;' : ''">{{
              scope.row.taps
            }}</span>
        </template>
      </el-table-column>
      <el-table-column v-if="adColumns.includes('installs')" label="广告安装" align="center"
                       prop="installs" :min-width="90" sortable>
        <template #default="scope">
          <span :style="scope.$index === list.length - 1 ? 'font-weight: bold;' : ''">{{
              scope.row.installs
            }}</span>
        </template>
      </el-table-column>
      <el-table-column v-if="adColumns.includes('newDownloads')" label="广告新装" align="center"
                       prop="newDownloads" :min-width="100" sortable>
        <template #default="scope">
          <span :style="scope.$index === list.length - 1 ? 'font-weight: bold;' : ''">{{
              scope.row.newDownloads
            }}</span>
        </template>
      </el-table-column>
      <el-table-column v-if="adColumns.includes('reDownloads')" label="重复安装" align="center"
                       prop="reDownloads"
                       :min-width="100" sortable>
        <template #default="scope">
          <span :style="scope.$index === list.length - 1 ? 'font-weight: bold;' : ''">{{
              scope.row.reDownloads
            }}</span>
        </template>
      </el-table-column>
      <el-table-column v-if="adColumns.includes('ttr')" label="点击率" align="center" prop="ttr"
                       :min-width="85" sortable>
        <template #default="scope">
          <span :style="scope.$index === list.length - 1 ? 'font-weight: bold;' : ''">{{
              percentage2(scope.row.ttr, 0)
            }}</span>
        </template>
      </el-table-column>
      <el-table-column v-if="adColumns.includes('conversionRate')" label="转化率" align="center"
                       prop="conversionRate"
                       :min-width="85" sortable>
        <template #default="scope">
          <span :style="scope.$index === list.length - 1 ? 'font-weight: bold;' : ''">{{
              percentage2(scope.row.conversionRate, 0)
            }}</span>
        </template>
      </el-table-column>
      <el-table-column v-if="adColumns.includes('avgCpaAmount')" label="转化费用"
                       :formatter="(row) => fenToYuanFormat(row.avgCpmCurrency, row.avgCpaAmount)"
                       align="center" prop="avgCpaAmount"
                       :min-width="100" sortable>
        <template #default="scope">
          <span :style="scope.$index === list.length - 1 ? 'font-weight: bold;' : ''">{{
              fenToYuanFormat(scope.row.avgCpmCurrency, scope.row.avgCpaAmount)
            }}</span>
        </template>
      </el-table-column>
      <el-table-column v-if="adColumns.includes('avgCptAmount')" label="点击付费"
                       :formatter="(row) => fenToYuanFormat(row.avgCpmCurrency, row.avgCptAmount)"
                       align="center" prop="avgCptAmount"
                       :min-width="100" sortable>
        <template #default="scope">
          <span :style="scope.$index === list.length - 1 ? 'font-weight: bold;' : ''">{{
              fenToYuanFormat(scope.row.avgCpmCurrency, scope.row.avgCptAmount)
            }}</span>
        </template>
      </el-table-column>
      <el-table-column v-if="adColumns.includes('avgCpmAmount')" label="千展费用"
                       :formatter="(row) => fenToYuanFormat(row.avgCpmCurrency, row.avgCpmAmount)"
                       align="center" prop="avgCpmAmount"
                       :min-width="100" sortable>
        <template #default="scope">
          <span :style="scope.$index === list.length - 1 ? 'font-weight: bold;' : ''">{{
              fenToYuanFormat(scope.row.avgCpmCurrency, scope.row.avgCpmAmount)
            }}</span>
        </template>
      </el-table-column>
      <!-- 销售指标 -->
      <el-table-column v-if="salesColumns.includes('profit')" label="利润" align="center"
                       prop="profit" :min-width="120"
                       sortable>
        <template #default="scope">
          <span :style="[
      scope.$index === list.length - 1 ? 'font-weight: bold;' : '',
      scope.row.profit > 0 ? 'color: red;' : scope.row.profit < 0 ? 'color: green;' : ''
    ]">
            {{ formatCurrency2(scope.row.profit, 0) }}
          </span>
        </template>
      </el-table-column>
      <el-table-column v-if="salesColumns.includes('ascProceeds')" label="订阅所得" align="center"
                       prop="ascProceeds"
                       :min-width="100" sortable>
        <template #default="scope">
          <span :style="scope.$index === list.length - 1 ? 'font-weight: bold;' : ''">{{
              formatCurrency2(scope.row.ascProceeds, 0)
            }}</span>
        </template>
      </el-table-column>
      <el-table-column v-if="salesColumns.includes('ascSales')" label="订阅销售额" align="center"
                       prop="ascSales" sortable
                       :min-width="100">
        <template #default="scope">
          <span :style="scope.$index === list.length - 1 ? 'font-weight: bold;' : ''">{{
              formatCurrency2(scope.row.ascSales, 0)
            }}</span>
        </template>
      </el-table-column>
      <el-table-column v-if="salesColumns.includes('ascRefundSales')" label="退款销售额"
                       align="center" prop="ascRefundSales"
                       :min-width="100" sortable>
        <template #default="scope">
          <span :style="scope.$index === list.length - 1 ? 'font-weight: bold;' : ''">{{
              formatCurrency2(scope.row.ascRefundSales, 0)
            }}</span>
        </template>
      </el-table-column>
      <el-table-column v-if="salesColumns.includes('ascRefundProceeds')" label="退款所得"
                       align="center"
                       prop="ascRefundProceeds" :min-width="100" sortable>
        <template #default="scope">
          <span :style="scope.$index === list.length - 1 ? 'font-weight: bold;' : ''">{{
              formatCurrency2(scope.row.ascRefundProceeds, 0)
            }}</span>
        </template>
      </el-table-column>
      <el-table-column v-if="salesColumns.includes('ascImpressions')" label="展示次数"
                       align="center" prop="ascImpressions"
                       :min-width="100" sortable>
        <template #default="scope">
          <span :style="scope.$index === list.length - 1 ? 'font-weight: bold;' : ''">{{
              scope.row.ascImpressions
            }}</span>
        </template>
      </el-table-column>
      <el-table-column v-if="salesColumns.includes('ascTaps')" label="点击次数" align="center"
                       prop="ascTaps"
                       :min-width="100" sortable>
        <template #default="scope">
          <span :style="scope.$index === list.length - 1 ? 'font-weight: bold;' : ''">{{
              scope.row.ascTaps
            }}</span>
        </template>
      </el-table-column>
      <el-table-column v-if="salesColumns.includes('ascInstalls')" label="首次安装" align="center"
                       prop="ascInstalls"
                       :min-width="100" sortable>
        <template #default="scope">
          <span :style="scope.$index === list.length - 1 ? 'font-weight: bold;' : ''">{{
              scope.row.ascInstalls
            }}</span>
        </template>
      </el-table-column>
      <el-table-column v-if="salesColumns.includes('naturallyInstalls')" label="自然新增"
                       align="center"
                       prop="naturallyInstalls" :min-width="100" sortable>
        <template #default="scope">
          <span :style="scope.$index === list.length - 1 ? 'font-weight: bold;' : ''">{{
              scope.row.naturallyInstalls
            }}</span>
        </template>
      </el-table-column>
      <el-table-column v-if="salesColumns.includes('ascReInstalls')" label="重新安装" align="center"
                       prop="ascReInstalls"
                       :min-width="100" sortable>
        <template #default="scope">
          <span :style="scope.$index === list.length - 1 ? 'font-weight: bold;' : ''">{{
              scope.row.ascReInstalls
            }}</span>
        </template>
      </el-table-column>
      <el-table-column v-if="salesColumns.includes('ascUptInstalls')" label="更新安装"
                       align="center" prop="ascUptInstalls"
                       :min-width="100" sortable>
        <template #default="scope">
          <span :style="scope.$index === list.length - 1 ? 'font-weight: bold;' : ''">{{
              scope.row.ascUptInstalls
            }}</span>
        </template>
      </el-table-column>
      <el-table-column v-if="salesColumns.includes('ascTtr')" label="点击率" align="center"
                       prop="ascTtr" :min-width="85"
                       sortable>
        <template #default="scope">
          <span :style="scope.$index === list.length - 1 ? 'font-weight: bold;' : ''">{{
              percentage2(scope.row.ascTtr, 0)
            }}</span>
        </template>
      </el-table-column>
      <el-table-column v-if="salesColumns.includes('ascConversionRate')" label="转化率"
                       align="center"
                       prop="ascConversionRate" :min-width="85" sortable>
        <template #default="scope">
          <span :style="scope.$index === list.length - 1 ? 'font-weight: bold;' : ''">{{
              percentage2(scope.row.ascConversionRate, 0)
            }}</span>
        </template>
      </el-table-column>
      <el-table-column v-if="salesColumns.includes('ascTrial')" label="试订数" align="center"
                       prop="ascTrial"
                       :min-width="85" sortable>
        <template #default="scope">
          <span :style="scope.$index === list.length - 1 ? 'font-weight: bold;' : ''">{{
              scope.row.ascTrial
            }}</span>
        </template>
      </el-table-column>
      <el-table-column v-if="salesColumns.includes('trialRate')" label="试订率" align="center"
                       prop="trialRate"
                       :min-width="85" sortable>
        <template #default="scope">
          <span :style="scope.$index === list.length - 1 ? 'font-weight: bold;' : ''">{{
              percentage2(scope.row.trialRate, 0)
            }}</span>
        </template>
      </el-table-column>
      <el-table-column v-if="salesColumns.includes('ascRenewal')" label="订阅数" align="center"
                       prop="ascRenewal"
                       :min-width="85" sortable>
        <template #default="scope">
          <span :style="scope.$index === list.length - 1 ? 'font-weight: bold;' : ''">{{
              scope.row.ascRenewal
            }}</span>
        </template>
      </el-table-column>
      <el-table-column v-if="salesColumns.includes('ascRefund')" label="退款数" align="center"
                       prop="ascRefund"
                       :min-width="85" sortable>
        <template #default="scope">
          <span :style="scope.$index === list.length - 1 ? 'font-weight: bold;' : ''">{{
              scope.row.ascRefund
            }}</span>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination :total="total" v-model:page="queryParams.pageNo"
                v-model:limit="queryParams.pageSize"
                @pagination="getList"/>
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <CampaignDataForm ref="formRef" @success="getList"/>
</template>

<style scoped>
.responsive-table {
  height: 600px;
}

@media (max-width: 768px) and (orientation: portrait) {
  .responsive-table {
    height: 400px;
    /* 移动设备竖屏高度 */
  }
}

@media (max-width: 768px) and (orientation: landscape) {
  .responsive-table {
    height: 300px;
    /* 移动设备横屏高度 */
  }
}
</style>

<script setup lang="ts">
import {DICT_TYPE, getDictOptions, getIntDictOptions} from '@/utils/dict'
import {fenToYuanFormat, formatCountryCode, formatCurrency2, percentage2} from '@/utils'
import download from '@/utils/download'
import {CampaignDataApi, CampaignDataVO} from '@/api/asasc/campaign'
import CampaignDataForm from './CampaignDataForm.vue'

/** 广告数据 列表 */
defineOptions({name: 'CampaignData'})

const message = useMessage() // 消息弹窗
const {t} = useI18n() // 国际化

// 获取当前日期和过去1天的日期，并格式化为 'yyyy-MM-dd HH:mm:ss'，使用北京时间
const getDefaultDateRange = () => {
  const toBeijingTime = (date) => {
    const offset = date.getTimezoneOffset() * 60000;
    // 28800000ms = 8 hours
    return new Date(date.getTime() + offset + 28800000);
  };

  const formatDateTime = (date) => {
    const y = date.getFullYear();
    const m = String(date.getMonth() + 1).padStart(2, '0');
    const d = String(date.getDate()).padStart(2, '0');
    const h = String(date.getHours()).padStart(2, '0');
    const min = String(date.getMinutes()).padStart(2, '0');
    const s = String(date.getSeconds()).padStart(2, '0');
    return `${y}-${m}-${d} ${h}:${min}:${s}`;
  };

  const endDate = toBeijingTime(new Date());
  const startDate = toBeijingTime(new Date());
  startDate.setDate(startDate.getDate() - 2); // 这里修正为 startDate
  endDate.setDate(endDate.getDate() - 2); // 这里修正为 startDate

  // 设置开始时间为 00:00:00，结束时间为 23:59:59
  startDate.setHours(0, 0, 0, 0);
  endDate.setHours(23, 59, 59, 999);

  console.log(formatDateTime(startDate), formatDateTime(endDate));
  return [formatDateTime(startDate), formatDateTime(endDate)];
};

const loading = ref(true) // 列表的加载中
const list = ref<CampaignDataVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 200,
  date: getDefaultDateRange(),
  countryOrRegion: undefined,
  campaignId: undefined,
  campaignName: undefined,
  isDeleted: undefined,
  campaignStatus: undefined,
  appName: undefined,
  adamId: undefined,
  servingStatus: undefined,
  countriesOrRegions: undefined,
  displayStatus: undefined,
  supplySources: undefined,
  adChannelType: undefined,
  orgId: undefined,
  createTime: [],
  countries: undefined,
  adamIds: undefined,
  dimension: undefined
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中
//默认所有的广告指标
const adColumns = ref(['localSpendAmount', 'impressions', 'taps', 'installs', 'ttr',
  'conversionRate', 'avgCpaAmount', 'avgCpmAmount', 'avgCptAmount'])
//默认所有的销售指标
const salesColumns = ref(["ascProceeds", "ascInstalls", "ascTrial", "ascRenewal", "ascRefund",
  "ascRefundProceeds", "naturallyInstalls", "profit"])
//默认维度
const dimensionColumns = ref(['country_or_region', 'adam_id'])


/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await CampaignDataApi.getCampaignDataPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  if (!queryParams.dimension || queryParams.dimension.length === 0) {
    message.error('维度至少要选一个');
    return;
  }
  if (!queryParams.date || queryParams.date.length === 0) {
    message.error('日期必须要选');
    return;
  }

  saveDimensionSession();

  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()

/** 导出按钮操作 */
const handleExport = async () => {
  if (!queryParams.dimension || queryParams.dimension.length === 0) {
    message.error('维度至少要选一个');
    return;
  }
  if (!queryParams.date || queryParams.date.length === 0) {
    message.error('日期必须要选');
    return;
  }

  saveDimensionSession();

  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await CampaignDataApi.exportCampaignData(queryParams)
    download.excel(data, '广告数据.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

// 保存维度设置到 localStorage
const saveDimensionSession = () => {
  localStorage.setItem('campaign.dimension', JSON.stringify(queryParams.dimension));

  dimensionColumns.value = JSON.stringify(queryParams.dimension);
};

// 保存列设置到 localStorage
const saveAdsColumnsSession = () => {
  localStorage.setItem('campaign.adColumns', JSON.stringify(adColumns.value));
};

const saveSalesColumnsSession = () => {
  localStorage.setItem('campaign.salesColumns', JSON.stringify(salesColumns.value));
};

/** 初始化 **/
onMounted(() => {
  const savedAdsColumns = localStorage.getItem('campaign.adColumns');
  if (savedAdsColumns) {
    adColumns.value = JSON.parse(savedAdsColumns);
  }

  const savedDimension = localStorage.getItem('campaign.dimension');
  if (savedDimension) {
    dimensionColumns.value = JSON.parse(savedDimension);
    queryParams.dimension = dimensionColumns.value;
  } else {
    queryParams.dimension = dimensionColumns.value;
  }

  const savedSalesColumns = localStorage.getItem('campaign.salesColumns');
  if (savedSalesColumns) {
    salesColumns.value = JSON.parse(savedSalesColumns);
  }

  getList()
})

/** 单元格样式 */
const cellStyle = ({row, column, rowIndex, columnIndex}) => {
  if (adColumns.value.includes(column.property)) {
    return {backgroundColor: '#f0f9ff', color: '#636a5f'};
  } else if (salesColumns.value.includes(column.property)) {
    return {backgroundColor: '#fff7e6', color: '#ff0000'};
  }

  return {};
};
</script>
